<?php


namespace app\admin\controller;


use app\util\ReturnCode;
use support\Response;
use app\model\MysqlField as MysqlFieldModel;

class MysqlField extends Base
{

    /**
     * 字段列表
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function index(): Response
    {
        $request = request();
        $limit = $request->get('size', config('apiwebman.ADMIN_LIST_DEFAULT'));
        $start = $request->get('page', 1);
        $keywords = $request->get('keywords', '');
        $type = $request->get('type', '');
        $status = $request->get('status', '');

        $obj = new MysqlFieldModel();
        if (strlen($status)) {
            $obj = $obj->where('app_status', $status);
        }
        if ($type) {
            switch ($type) {
                case 1:
                    //字段名称
                    $obj = $obj->whereLike('name', "%{$keywords}%");
                    break;
                case 2:
                    //字段标题
                    $obj = $obj->whereLike('title', "%{$keywords}%");
                    break;
                case 3:
                    //字段类型
                    $obj = $obj->where('type', $keywords);
                    break;
            }
        }
        $listObj = $obj->order('id', 'DESC')->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list' => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    public function add(): Response
    {
        $request = request();
        $postData = $request->post();
        $data = [
            'table' => $postData['table'],
            'name' => $postData['name'],
            'title' => $postData['title'],
            'type' => $postData['type'],
            'define' => $postData['define'],
            'value' => $postData['value'],
            'options' => $postData['options'],
            'tips' => $postData['tips'],
            'fixed' => $postData['fixed'],
            'show' => $postData['show'],
            'model' => $postData['model'],
            'level' => $postData['level'],
            'option' => $postData['option'],
            'key' => $postData['key'],
            'create_time' => time(),
        ];

        $res = MysqlFieldModel::create($data);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

}
